from zipline.api import order, symbol, record
from zipline.finance import commission, slippage

def initialize(context):
    # Set benchmark and trading parameters
    context.asset = symbol('AAPL')  # Example asset, can be parameterized
    context.fast_period = 12
    context.slow_period = 26
    context.signal_period = 9
    
    # Initialize state variables
    context.ema_fast = None
    context.ema_slow = None
    context.ema_signal = None
    context.macd_line = None
    
    # Set trading costs
    context.set_commission(commission.PerShare(cost=0.001, min_trade_cost=1))
    context.set_slippage(slippage.FixedSlippage(spread=0.01))

def handle_data(context, data):
    # Get historical close prices
    prices = data.history(context.asset, 'close', 
                          bar_count=max(context.slow_period, context.signal_period) + 10, 
                          frequency='1d')
    
    # Calculate EMAs
    if context.ema_fast is None:
        context.ema_fast = prices.ewm(span=context.fast_period, adjust=False).mean()[-1]
    else:
        context.ema_fast = (prices[-1] * (2/(context.fast_period+1)) + 
                           context.ema_fast * (1 - 2/(context.fast_period+1)))
    
    if context.ema_slow is None:
        context.ema_slow = prices.ewm(span=context.slow_period, adjust=False).mean()[-1]
    else:
        context.ema_slow = (prices[-1] * (2/(context.slow_period+1)) + 
                           context.ema_slow * (1 - 2/(context.slow_period+1)))
    
    # Calculate MACD line
    context.macd_line = context.ema_fast - context.ema_slow
    
    # Calculate signal line
    if context.ema_signal is None:
        context.ema_signal = context.macd_line
    else:
        context.ema_signal = (context.macd_line * (2/(context.signal_period+1)) + 
                             context.ema_signal * (1 - 2/(context.signal_period+1)))
    
    # Get current position
    current_position = context.portfolio.positions[context.asset].amount
    
    # Trading logic
    if context.macd_line > context.ema_signal and current_position <= 0:
        order(context.asset, 100)  # Buy signal (golden cross)
    elif context.macd_line < context.ema_signal and current_position > 0:
        order(context.asset, -100)  # Sell signal (death cross)
    
    # Record values for analysis
    record(macd=context.macd_line, signal=context.ema_signal)